package chat;

import java.net.Socket;
import java.net.ServerSocket;
import java.io.*;
import java.util.Vector;
public class Server
{
	ServerSocket server;
	SocketManager manager=new SocketManager();
	public Server()
	{
		
	}
	void startServer()
	{
		try
		{
			server=new ServerSocket(5000);
			System.out.println("建立端口");
			
			System.out.println("等待客户端连接...");
			while(true)
			{
				
				Socket socket=server.accept();
				System.out.println("客户端已连接");
				new ChatThread(socket).start();
				manager.add(socket);
				manager.sendClientNum();
			}
		}
		catch(Exception e)
		{
			System.err.println("发生异常:"+e);
			e.printStackTrace();
		}
	}
	class ChatThread extends Thread
	{
		Socket socket;
		BufferedReader reader;
		PrintWriter writer;
		ChatThread(Socket socket)
		{
			this.socket=socket;
		}
		public void run()
		{
			try
			{
				reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
				writer=new PrintWriter(socket.getOutputStream(),true);
				String message;
				while((message=reader.readLine())!=null)
				{
					System.out.println(message);
					manager.sendMessage(message);
				}
			}
			catch(Exception e)
			{
			   System.err.println("发生异常:"+e);
			   e.printStackTrace();
			}
			finally
			{
				try
				{
					manager.remove(socket);
					if(reader!=null)
						reader.close();
					if(writer!=null)
					writer.close();
					if(socket!=null)
					socket.close();
					reader=null;
					writer=null;
					socket=null;
					System.out.println("用户下线");
					manager.sendClientNum();
			
				}
				catch(Exception e)
				{
				    System.err.println("发生异常:"+e);
			        e.printStackTrace();
				}
			}
		}
	}
	class SocketManager extends Vector
	{
		SocketManager()
		{
			
		}
		void add(Socket socket)
		{
			super.add(socket);
		}
		void remove(Socket socket)
		{
			super.remove(socket);
		}
		synchronized void sendMessage(String message)
		{
			PrintWriter writer=null;
			Socket socket;
			for(int i=0;i<size();i++)
			{
				socket=(Socket)elementAt(i);
				try
				{
					writer=new PrintWriter(socket.getOutputStream(),true);
					
				}
				catch(IOException e)
				{
					System.err.println("发生异常:"+e);
			        e.printStackTrace();
				}
				if(writer!=null)
				writer.println(message);
			}
		}
		synchronized void sendClientNum()
		{
			String clientNum="当前在线人数为"+size();
			System.out.println(clientNum);
			sendMessage(clientNum);
			
		}
	}
	public static void main(String[] args)
	{
		Server server=new Server();
		server.startServer();
	}
}
